package com.lingnan.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.lingnan.common.utils.ResultEntity;
import com.lingnan.service.VideoSerivce;
import com.lingnan.servicebase.excetioncontrooller.LingNanException;
import com.lingnan.utils.ConstantPropertiesUtil;
import com.lingnan.utils.InitObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 视频点播
 *
 * @author zzd
 */
@RestController
@RequestMapping("/vodService/video")
@Api("阿里视频点播功能")
@CrossOrigin
public class VideoController {

    @Autowired
    private VideoSerivce videoSerivce;

    /**
     * 视频上传功能
     *
     * @return
     */
    @PostMapping("uploading")
    @ApiOperation("视频上传")
    public ResultEntity uploading(MultipartFile file) {
        // 判断文件是否为空
        if (null == file) {
            throw new LingNanException(20001, "上传文件失败");
        }
        try {
            String videoId = videoSerivce.uploading(file);
            if (null == videoId || videoId.length() <= 0) {
                return ResultEntity.error().message("上传视频失败!");
            }
            return ResultEntity.ok().message("上传视频成功!").data("videoId", videoId);

        } catch (Exception e) {

            e.printStackTrace();

            return ResultEntity.error();

        }
    }

    /**
     * 根据视频ID在阿里云删除视频
     * @param videoSourceId
     * @return
     */
    @DeleteMapping("deleteVideoByVideoSourceId/{videoSourceId}")
    @ApiOperation("根据视频ID在阿里云删除视频")
    public ResultEntity deleteVideoByVideoSourceId(@PathVariable("videoSourceId") String videoSourceId){

        try {
            // 创建初始化对象
            DefaultAcsClient client = InitObject.initVodClient(ConstantPropertiesUtil.KEY_ID, ConstantPropertiesUtil.KEY_SECRET);
            // 创建request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            // 设置需要删除的视频id
            request.setVideoIds(videoSourceId);
            // 使用初始化对象执行
            client.getAcsResponse(request);
            // 返回删除成功信息
            return ResultEntity.ok();
        } catch (ClientException e) {
            e.printStackTrace();
            // 删除失败
            throw new LingNanException(20001,"删除视频失败");
        }
    }

    /**
     * 批量删除视频
     * @param videoSourceIdList 所有视频ID
     * @return
     */
    @DeleteMapping("deleteAllVideo")
    @ApiOperation("批量删除视频")
    public ResultEntity deleteAllVideo(@RequestParam("videoSourceIdList") List<String> videoSourceIdList){
        videoSerivce.deleteAllVideo(videoSourceIdList);
        return ResultEntity.ok();
    }


}
